
package org.socratotor.service.cm;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.japril.jutil.CharArrayPrintWriter;
import org.soekrat.engine.socraton.Socraton;
import org.soekrat.engine.socraton.SocratonsXml;

@SuppressWarnings("serial")
public final class CmServlet extends HttpServlet
{
  /**
   * <p>
   *   Constructor.
   * </p> 
   */
  public CmServlet(){}

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException 
  {
    String xml=req.getParameter("xml");
    if (xml==null) respondPlainText("missing xml parameter", res);
    
    URL url=new URL(xml);
    process(url.openStream(), res);
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException 
  {
    process(req.getInputStream(), res);
  }
  
  private void process(InputStream is, HttpServletResponse res)
    throws IOException
  {
    SocratonsXml xml=new SocratonsXml();
    List<Socraton> socratons=xml.parse(is);
    String txt=toString(socratons);
    respondPlainText(txt, res);
  }
  
  private void respondPlainText(String txt, HttpServletResponse res)
    throws IOException
  {
    res.setContentType("text/plain");
    PrintWriter pw=res.getWriter();
    pw.println(txt);
    pw.flush();
  }
  
  private static String toString(List<Socraton> l)
  {
    CharArrayPrintWriter capw=new CharArrayPrintWriter();
    for (Socraton socraton : l) capw.println(socraton);
    return capw.toString();
  }
  
}
